package cn.net.ecode.modules.msg.service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.directwebremoting.ui.dwr.Util;

import cn.net.ecode.common.persistence.Page;
import cn.net.ecode.common.utils.DateUtils;
import cn.net.ecode.modules.msg.entity.Message;
import cn.net.ecode.modules.msg.entity.MessageRecord;
import cn.net.ecode.modules.msg.entity.MsgPush;
import cn.net.ecode.modules.msg.util.MessageUtils;
import cn.net.ecode.modules.sys.entity.User;
import cn.net.ecode.modules.sys.utils.UserUtils;

import com.google.common.collect.Maps;

/**
 * 消息推送服务
 * @author ThinkGem
 * @version	2015-5-30
 */
@RemoteProxy
public class MsgPushService {

	/**
	 * 登录首页后，添加scriptSessionId
	 * @return
	 */
	@RemoteMethod
	public MsgPush loginIndex() {
		final User user = UserUtils.getUser();
		ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
		scriptSession.setAttribute("userCode", user.getUserCode());
		scriptSession.setAttribute("userName", user.getUserName());

		// 初始所有未送达的消息。重新推送一遍
		ScriptBuffer script = new ScriptBuffer();
		List<MessageRecord> mrList = MessageUtils.getUndeliveredList(user.getUserCode());
		Message message = new Message();
		for (int i = mrList.size() - 1; i >= 0; i--){
			MessageRecord messageRecord = mrList.get(i);
			message = messageRecord.getMessage() == null ? new Message() : messageRecord.getMessage();
			script.appendCall("receiveMsg", message, messageRecord.getId());
		}
		scriptSession.addScript(script);
		
		// 取前10条未读消息记录。返回未读总条数
		Page<MessageRecord> p = MessageUtils.getUnReadPage(user.getUserCode(), 10);
		MsgPush msg = new MsgPush();
		msg.setCount(p.getCount());
		msg.setList(p.getList());
		return msg;
	}

	/** 
	 * 消息推送 
	 * @param receiver 接收者ID
	 * @param senderName 发送人名称
	 * @param message 信息标题
	 */
	@RemoteMethod
	public boolean sendMsg(final String receiver, final Message message, final String recordId) {
		Browser.withAllSessionsFiltered(new ScriptSessionFilter() {
			public boolean match(ScriptSession session) {
				String userCode = (String)session.getAttribute("userCode");
				return userCode != null && userCode.equals(receiver);
			}
		}, new Runnable() {
			public void run() {
				ScriptBuffer script = new ScriptBuffer();
				script.appendCall("receiveMsg", message, recordId);
				Collection<ScriptSession> sessions = Browser.getTargetSessions();
				for (ScriptSession scriptSession : sessions) {
					scriptSession.addScript(script);
				}
			}
		});
		return true;
	}

	/** 
	 * 接收到消息，添加消息送达时间
	 * @param id 
	 */
	@RemoteMethod
	public boolean deliveredMsg(String recordId) {
		return MessageUtils.deliveredMsg(recordId);
	}

	/** 
	 * 读取消息回调，设置消息读取时间
	 * @param id 
	 */
	@RemoteMethod
	public boolean readMsg(String recordId) {
		return MessageUtils.readMsg(recordId);
	}

	/**
	 * Chat登录
	 * @return
	 */
	@RemoteMethod
	public boolean login() {
		User user = UserUtils.getUser();
		ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
		scriptSession.setAttribute("userCode", user.getUserCode());
		scriptSession.setAttribute("userName", user.getUserName());
		
		// 添加数据到用户列表
		Browser.withAllSessions(new Runnable() {
			public void run() {
				Map<String, String[]> users = Maps.newHashMap();
				for (ScriptSession scriptSession : Browser.getTargetSessions()) {
					String userCode = (String) scriptSession.getAttribute("userCode");
					String userName = (String) scriptSession.getAttribute("userName");
					users.put(userCode, new String[] { userCode, userName });
				}
				Util.removeAllOptions("users");
				Util.addOptions("users", users.values(), "0", "1");
//				ScriptSessions.addFunctionCall("addUser", user.values());
//				System.out.println("scriptSessionId size: " + users.size());
			}
		});
		return true;
	}

	/**
	 * Chat发送消息
	 * @param receiver 接收人
	 * @param message 消息内容
	 * @return
	 */
	@RemoteMethod
	public boolean sendMsg(final String receiver, final String message, final String id) {
		Browser.withAllSessionsFiltered(new ScriptSessionFilter() {
			public boolean match(ScriptSession session) {
				String userCode = (String)session.getAttribute("userCode");
				return userCode != null && userCode.equals(receiver);
			}
		}, new Runnable() {
			public void run() {
				User user = UserUtils.get(receiver);
				ScriptBuffer script = new ScriptBuffer();
				script.appendCall("receiveMsg", user.getUserName(), message, DateUtils.getDateTime(), id);
				Collection<ScriptSession> sessions = Browser.getTargetSessions();
				for (ScriptSession scriptSession : sessions) {
					scriptSession.addScript(script);
				}
			}
		});
		return true;
	}
}
